package com.yx.cloud.activity;

import android.animation.Animator;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

//import com.yx.cloud.BuildConfig;
import com.iot.common.utils.Event;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.AppUpdateBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.AboutusActivityBinding;
import com.yx.cloud.utils.AnimationtUtils;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.OkhttpUtil;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.utils.VersionUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 创建时间 : 2018/12/26.
 * 创建人 :
 * 功能描述 :关于界面
 */
public class AboutUsActivity extends BaseActivity implements View.OnClickListener {

    private final static String TAG = "AboutUsActivity";
    private Dialog dialog;
    AppUpdateBean appUpdateBean;
    private AboutusActivityBinding binding;

    @Override
    protected void onResume() {
        super.onResume();
//        if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
//            detectNewVersions();
//        }
    }

    @Override
    protected void onCreate() {
        binding = AboutusActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        initWidget();
    }

    private void initWidget() {
        binding.tvVersion.setText("V" + VersionUtils.getClientVersion(this));

//        binding.tvAboutusURL.setText(BuildConfig.WEBSITE);
//        binding.tvAboutsContactWay.setText(BuildConfig.PHONE);

        //判断系统动画是否开启
        boolean powerSaveMode = AnimationtUtils.isPowerSaveMode(this);
        if (!powerSaveMode) {
            binding.lottieAnimationView.addAnimatorListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    binding.lottieAnimationView.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        }

        binding.ivAboutUsReturn.setOnClickListener(this);
        binding.rlServiceTel.setOnClickListener(this);
        binding.rlAppUpdate.setOnClickListener(this);
        binding.rlAboutusWorking.setOnClickListener(this);
        binding.rlPrivacyPolicy.setOnClickListener(this);
        binding.rlServiceAgreement.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_aboutUsReturn:
                Intent_utils.backIntent(this);
                break;
            case R.id.rl_serviceTel:
                String phoneNum = binding.tvAboutsContactWay.getText().toString().trim();
                contactWayHintDialog(getString(R.string.MY_ContactDetails_Tip) + phoneNum);
                break;
            case R.id.rl_app_update:
                //binding.lottieAnimationView.setVisibility(View.VISIBLE);
                detectNewVersions();
                break;
            case R.id.rl_aboutusWorking:

                String url = binding.tvAboutusURL.getText().toString().trim();
                Log.d(TAG, "网页地址: " + url);
                //从其他浏览器打开
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("http://" + url);
                intent.setData(content_url);
                startActivity(intent);

                break;
            case R.id.rl_privacyPolicy:
                //隐私政策
                Intent_utils.enterIntentContext(this, ServerAndPrivacyActivity.class, "Server_Privacy", "Privacy");
                break;
            case R.id.rl_serviceAgreement:
                //服务协议
                Intent_utils.enterIntentContext(this, ServerAndPrivacyActivity.class, "Server_Privacy", "Server");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_REQUEST_APP_UPDATE_ABOUT:
                if (SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_APP_HAS_UPPER_VERSION, false)) {
                    //  有新版本 0：App 提醒升级 2：App 强制升级
                    String mContent = getString(R.string.MY_Version_New_Tip).replace("{X}",appUpdateBean.getVersion());
                    newAPPVersionsHintDialog(this, mContent, getString(R.string.MY_Version_New), getString(R.string.U_NoUpdate), getString(R.string.U_Update), appUpdateBean.getDownLoadUrl());
                } else {
                    ToastUtil.show(AboutUsActivity.this, getString(R.string.MO_New_Current), Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    /**
     * 联系方式Dialog
     */
    private void contactWayHintDialog(String dialogTitle) {
        dialog = new Dialog(AboutUsActivity.this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_centered_dialogTitle);

        mTvDialogTitle.setText(dialogTitle);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String serviceTel = binding.tvAboutsContactWay.getText().toString().trim();
                Intent intentService = new Intent(Intent.ACTION_DIAL);
                Uri dataS = Uri.parse("tel:" + serviceTel);
                intentService.setData(dataS);
                startActivity(intentService);

                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void detectNewVersions() {
        if (appUpdateBean == null) {
            appUpdateBean = new AppUpdateBean();
        }
        //从官网获取版本号比对更新
        OkhttpUtil.get("https://www.inxni.com/appvision/android", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("liunianheaaaa", "error is " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.d(TAG, "json is " + json);
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    if (jsonObject.has("data")) {
                        String updateStr = jsonObject.getString("data");
                        Log.d(TAG, "data is " + json);
                        JSONObject updateObject = new JSONObject(updateStr);
                        if (updateObject.has("version")) {
                            String newVersion = updateObject.getString("version");
                            String currentVersion = AppUtil.getVersionName(AboutUsActivity.this);
                            int result = AppUtil.compareVersion(newVersion, currentVersion);
                            Log.d(TAG, "compare result is " + result);
                            appUpdateBean.setVersion(newVersion);
                            appUpdateBean.setDownLoadUrl(updateObject.getString("downloadUrl"));
                            if (result == 1) {
                                String forceUpdate = updateObject.getString("forceUpgrade");
                                Log.d(TAG, "forceUpgrade is " + forceUpdate);
                                Event.newBuilder().type(Event.MESSAGE_TYPE_REQUEST_APP_UPDATE_ABOUT).content(appUpdateBean).send();
                                SharedPrefsUtil.putValue(AboutUsActivity.this, Constants.NOT_READ_TAG, Constants.KEY_APP_HAS_UPPER_VERSION, true);
                            } else {
                                SharedPrefsUtil.putValue(AboutUsActivity.this, Constants.NOT_READ_TAG, Constants.KEY_APP_HAS_UPPER_VERSION, false);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 新版本Dialog
     */
    public void newAPPVersionsHintDialog(Context context, String content, String
            dialogTitle, String str1, String str2, String url) {
        if (dialog == null) {
            dialog = new Dialog(context);
        }
        if (dialog.isShowing()) {
            return;
        }
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mContent = dialog.findViewById(R.id.tv_content);

        mTvDialogTitle.setText(dialogTitle);
        mContent.setText(content);

        mBtnOutLoginCancel.setText(str1);
        mBtnOutLoginConfirm.setText(str2);
        mBtnOutLoginConfirm.setTextColor(getResources().getColor(R.color.button_color2));

        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "helpServiceTelHintDialog ------");
                //从其他浏览器打开
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
                dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

}
